package web;

import cz.muni.fi.pv168.ContactManager.Person;
import cz.muni.fi.pv168.ContactManager.PersonManager;
import cz.muni.fi.pv168.ContactManager.PersonManagerImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/spracovanie")
public class ContactServlet extends HttpServlet {

    private PersonManagerImpl manager;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        PersonManager manager = (PersonManager) getServletContext().getAttribute("manager");

        String hlaska = "Insert new person";
        if (request.getParameterMap().containsKey("firstname") && request.getParameterMap().containsKey("lastname")) {
            Person person = new Person();
            person.setFirstName(request.getParameter("firstname"));
            person.setLastName(request.getParameter("lastname"));
            hlaska = "Person inserted.";
            try
            {
                manager.createPerson(person);
            }
            catch(SQLException ex) {hlaska = "Failed to insert!";}

        }

        request.setAttribute("hlaska", hlaska);

        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PersonManager manager = (PersonManager) getServletContext().getAttribute("manager");

        request.setAttribute("persons", manager.findAllPersons());

        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
}